﻿#include "qt_log.h"
#include <QMutex>
#include <iostream>


qt_log_t  qt_log_cfg;                           //日志配置
QString qt_log_path = "";                       //日志路径
QString qt_log_txt_path = "";                   //日志文件路径
QStringList qt_log_file_list;                   //日志文件列表
static bool qt_log_inited = false;              //日志模块初始化标志
static int qt_line_index = 1;                   //日志条目索引
static char qt_log_buf[16 * 1024] = { '\0' };   //输出带换行

static int m_LogLevel = 1;
static QString m_LogFile = QString("./log/%1.log").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss"));
QMutex m_LogMutex;

void DlMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg)
{
	if (type < m_LogLevel)
	{
		return;
	}

	QString log_info;
	switch (type)
	{
	case QtDebugMsg:
		log_info = QString("%1.%2:%3").arg(qt_line_index).arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"), msg);
		break;

	case QtWarningMsg:
		log_info = QString("%1.[Warning]%2:%3").arg(qt_line_index).arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"), msg);
		break;

	case QtCriticalMsg:
		log_info = QString("%1.[Critical]%2:%3").arg(qt_line_index).arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"), msg);
		break;

	case QtFatalMsg:
		log_info = QString("%1.[Fatal]%2:%3").arg(qt_line_index).arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"), msg);
	}
	//为了线程安全
	m_LogMutex.lock();
	QFile outFile(m_LogFile);
	outFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text);
	QTextStream ts(&outFile);
	ts << log_info << "\n";
	outFile.close();

	if (qt_line_index >= 1024) {
		qt_line_index = 0;
		m_LogFile = QString("./log/%1.log").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss"));
	}
	qt_line_index++;

	//QTextCodec* pCodec = QTextCodec::codecForName("gb2312");
	//QByteArray arr = pCodec->fromUnicode(log_info);
	//QStringConverter::
	//std::string cstr = arr.data();
	//std::cout << cstr << std::endl;
	m_LogMutex.unlock();
}
//默认调试级别为warning及以上才会写入日志文件，默认log文件名为程序启动时间命名的log文件
void logInit(QString logFile, int logLevel)
{
	if ((logLevel < 0) || (logLevel > 3))
	{
		m_LogLevel = 1;
	}
	else
	{
		m_LogLevel = logLevel;
	}
	if (!logFile.isEmpty())
	{
		m_LogFile = logFile;
	}
	QDir dir("./log");
	if (!dir.exists())
	{
		bool ok = dir.mkpath("./log");
	}
	qInstallMessageHandler(DlMessageHandler);
	qt_log_inited = true;
}

void qt_log(int level, const char* fmt, ...)
{
	if (!qt_log_inited) return;

	//if (level > m_LogLevel)
	//{
		//	return;
	//}
	va_list ap;
	va_start(ap, fmt);
	vsnprintf(qt_log_buf, 16 * 1024, fmt, ap);
	va_end(ap);
	//auto str = QString::fromUtf8(qt_log_buf);
	qDebug() << QString::fromUtf8(qt_log_buf);
}
